<template>
  <div class="home" id="home">
    <router-view class="container"></router-view>
    <p class="botton-title" v-if="$route.path=='/studyIndex'">
      解放家长，高效学习，智慧1+1！
    </p>
    <footer class="home-footer" v-if="showFooter">
      <p>
        Copyright © 2003-2021 福州市智慧一加一教育科技有限公司.All Rights Reserved
        湘ICP备2023007847号-3
      </p>
    </footer>
    <el-dialog
      title="提示"
      :visible.sync="dialogNotification"
      width="480px"
      :before-close="notificationTimer.close"
      class="study-reminder-dialog"
    >
      <span class="text"
        >您已经学习50分钟了，<br />
        注意劳逸结合，休息一下吧！
      </span>
      <div>
        <img src="@/assets/img/study-reminder.png" alt="" />
      </div>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="dialogAsleepTimer"
      width="480px"
      :before-close="asleepTimer.close"
      class="study-reminder-dialog"
    >
      <span class="text">同学，还在学习吗？<br />您已经长时间没有操作了！</span>
      <div>
        <img src="@/assets/img/study-reminder.png" alt="" />
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import Header from "../components/Header";
import { addEnergy, getLevelTime, addEnergyOnline } from "@/api/game";
import sha256 from "crypto-js/sha256";
export default {
  name: "Home",
  data() {
    return {
      showFooter: true,
      onlineTimer: null,
      /*连续学习50分钟提示*/
      notificationTimer: null,
      dialogNotification: false,
      /*十分钟不动提示*/
      asleepTimer: null,
      dialogAsleepTimer: false,
    };
  },
  // components: { Header },
  methods: {
    setShowFooter(route) {
      // console.log(route,"route");
      const reg = RegExp(/typingGame/);
      if (
        route.path.match(reg) ||
        (route.name == "testReport" && !route.query.isFirst)
      ) {
        this.showFooter = false;
      } else {
        this.showFooter = true;
      }
    },
    verifyBookData() {
      let bookData = JSON.parse(localStorage.getItem("bookData"));
      if (!bookData) {
        this.$router
          .push({
            path: "/",
          })
          .catch((error) => {
            console.log(error);
            this.$router.go(0);
          });
      }
    },
    getLevelTime() {
      return new Promise((reslove, reject) => {
        getLevelTime()
          .then((res) => {
            reslove(res);
          })
          .catch(() => {
            reject();
          });
      });
    },
    addEnergy() {
      return new Promise((reslove, reject) => {
        addEnergy()
          .then((res) => {
            reslove(res);
          })
          .catch(() => {
            reject();
          });
      });
    },
    addEnergyOnline() {
      return new Promise((reslove, reject) => {
        addEnergyOnline()
          .then((res) => {
            reslove(res);
          })
          .catch(() => {
            reject();
          });
      });
    },
    //在线定时器
    setOnlineTimer() {
      let that = this;
      // 在线时长定时器
      this.onlineTimer = {
        timeout: 60 * 60,
        timeoutObj: null,
        startTime: null,
        reset: function() {
          clearInterval(this.timeoutObj);
          return this;
        },
        start: function() {
          this.startTime = new Date().getTime();
          that.$store.commit("SET_STARTTIMEGAME", this.startTime);
          this.timeoutObj = setTimeout(async () => {
            // 加体力
            let res = await that.addEnergy();
            if (res.code == 200) {
              that.$bus.$emit("addEnergy");
              this.timeout = 60 * 60;
              that.onlineTimer.reset().start();
            }
          }, this.timeout * 1000);
        },
      };
    },
    setLevelTime() {
      let params = {};
      params.key = parseInt(Math.random() * 10000, 10);
      params.timestamp = new Date().getTime();
      params.sign = sha256(
        `${params.key}:guoshi88-plus:${params.timestamp}`
      ).toString();
      if (!this.onlineTimer.startTime) {
        return;
      }
      let residue = parseInt(
        (new Date().getTime() - this.onlineTimer.startTime) / 1000 / 60
      );
      let data = {
        token: this.$store.getters.token.substring(6).trim(),
        residue,
      };
      let beaconStr = JSON.stringify(data);
      let url = `${this.baseAPI}leave/updateLeaveTime`;
      const queryStr = Object.keys(params)
        .reduce((ary, key) => {
          if (params[key]) {
            ary.push(
              encodeURIComponent(key) + "=" + encodeURIComponent(params[key])
            );
          }
          return ary;
        }, [])
        .join("&");
      url += `?${queryStr}`;
      let res = navigator.sendBeacon(url, beaconStr);
      console.log(res);
    },
    beforeunloadFun() {
      if (this.$store.getters.token) {
        // 发送离线请求
        this.setLevelTime();
      }
    },
    /**
     * 连续学习50分钟提示
     * start
     */
    setNTimer() {
      let that = this;
      // 学习50分钟
      this.notificationTimer = {
        //3000000
        timeout: 50 * 60 * 1000,
        timeoutObj: null,
        closeTimerObj: null,
        reset: function() {
          if (this.timeoutObj) {
            clearTimeout(this.timeoutObj);
          }
          if (this.closeTimerObj) {
            clearTimeout(this.closeTimerObj);
          }
          return this;
        },
        start: function() {
          let self = this;

          self.timeoutObj = setTimeout(() => {
            that.dialogNotification = true;
            self.closeTimerObj = setTimeout(() => {
              self.close();
            }, 5000);
          }, self.timeout);
        },
        close: function() {
          that.dialogNotification = false;
          that.notificationTimer.reset().start();
        },
      };
    },
    /**
     * 连续学习50分钟提示
     * end
     */
    /**
     * 十分钟不动提示
     * start
     */
    setATimer() {
      let that = this;
      //十分钟不动
      this.asleepTimer = {
        timeout: 60 * 1000,
        // timeout: 6000,
        timeoutObj: null,
        closeTimeObj: null,
        newTime: new Date().getTime(),
        oldTime: new Date().getTime(),
        outTime: 10 * 60 * 1000,
        // outTime: 6000,
        reset: function() {
          if (this.timeoutObj) {
            clearTimeout(this.timeoutObj);
          }
          if (this.closeTimeObj) {
            clearTimeout(this.closeTimeObj);
          }
          return this;
        },
        start: function() {
          let self = this;
          self.timeoutObj = setTimeout(() => {
            self.newTime = new Date().getTime();
            if (self.newTime - self.oldTime > self.outTime) {
              that.dialogAsleepTimer = true;
              that.notificationTimer.reset();
              that.onlineTimer.reset();
              self.reset();
            } else {
              self.reset().start();
            }
          }, this.timeout);
        },
        close: () => {
          that.dialogAsleepTimer = false;
          that.asleepTimer.reset().start();
          that.notificationTimer.reset().start();
          that.onlineTimer.reset().start();
        },
      };
    },
    /**
     * 十分钟不动提示
     * end
     */
    domEvent() {
      this.asleepTimer.oldTime = new Date().getTime();
    },
  },
  async created() {
    window.addEventListener("mousemove", this.domEvent);
    window.addEventListener("click", this.domEvent);
    // 连续学习50分钟提示
    this.setNTimer();
    // 十分钟不动提示
    this.setATimer();
    if (!this.$store.getters.isTeacher) {
      await this.addEnergyOnline();
      this.setOnlineTimer();
      let res = await this.getLevelTime();
      this.onlineTimer.timeout = (60 - res.data) * 60;
      this.onlineTimer.reset().start();
      window.addEventListener("beforeunload", this.beforeunloadFun);
      // this.$socket.reconnect();
      if (!this.notificationTimer.timeoutObj) {
        this.notificationTimer.reset().start();
      }
      if (!this.asleepTimer.timeoutObj) {
        this.asleepTimer.reset().start();
      }
    }
  },
  beforeDestroy() {
    if (!this.$store.getters.isTeacher) {
      this.onlineTimer.reset();
      // this.$socket.close();
      this.notificationTimer.reset();
      this.asleepTimer.reset();
    }
  },
  // studyIndex overallReport
  // components: { Header },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (
        to.name !== "studyIndex" &&
        to.name !== "overallReport" &&
        to.name !== "login"
      ) {
        vm.verifyBookData();
      }
      vm.setShowFooter(to);
    });
  },
  beforeRouteUpdate(to, from, next) {
    var vm = this;
    vm.setShowFooter(to);
    if (
      to.name !== "studyIndex" &&
      to.name !== "overallReport" &&
      to.name !== "login"
    ) {
      vm.verifyBookData();
    }
    next();
  },
  beforeRouteLeave(to, from, next) {
    // ...

    next();
  },
};
</script>
<style scoped>
.botton-title {
  background: #ffff;
  width: 100%;
  font-size: 16px;
  font-family: Source Han Serif CN;
  font-weight: 600;
  color: #0a193a;
  line-height: 60px;
  text-align: center;
  /* position: fixed;
  bottom: 40px;
  left: 0; */
}
</style>
